/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.log;

import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;

/**
 * Configure environment event monitoring
 * ApplicationEnvironmentPreparedEvent: the corresponding environment has been prepared,
 * but the context has not been created at this time.
 *
 * @author lvyh 2021/03/20.
 */
public class LogEnvPrepareApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {

    /**
     * The main purpose of ApplicationEnvironmentPreparedEvent publishing
     * is to load the configuration file and initialize the log system.
     */
    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment configurableEnvironment = event.getEnvironment();
        prepareEnvironment(configurableEnvironment);
        defaultConsoleLoggers();
    }

    @Override
    public int getOrder() {
        // Must be invoked after ConfigFileApplicationListener
        return Ordered.HIGHEST_PRECEDENCE + 100;
    }

    private void prepareEnvironment(ConfigurableEnvironment environment) {
        for (PropertySource<?> propertySource : environment.getPropertySources()) {
            if (propertySource instanceof EnumerablePropertySource) {
                for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
                }
            }
        }
    }

    private void defaultConsoleLoggers() {

    }
}
